package com.ad.admin.interview_viewpage;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.ad.admin.adapter.MyPagerAdapter;
import com.ad.admin.adapter.QuestionAdapter;
import com.ad.admin.util.Globals;
import com.ad.admin.util.QuestionDao;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    //ViewPage设置页面三元素  和listView相似
    private ViewPager viewPager;
    private List<View> allViews;
    private MyPagerAdapter pagerAdapter;


    //页面底部按钮背景图片的2个数组;b--按钮选中前,a--按钮选中后
    private int[] bottomImgs = new int[]{R.drawable.bottombtn01b, R.drawable.bottombtn02b, R.drawable.bottombtn03b};
    private int[] bottomImgsSelected = new int[]{R.drawable.bottombtn01a, R.drawable.bottombtn02a, R.drawable.bottombtn03a};
    //页面按钮数组
    private Button btn[] = new Button[3];

    //顶部文字和对应的数组
    private TextView top_title;
    String[] allTitles = {"程序员面试宝典","面试题库","搜索"};



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //布局文件中需要由id得到对象的初始化
        top_title = (TextView)findViewById(R.id.head_title);
        //底部按钮初始化
        btn[0]=(Button)findViewById(R.id.home_btn);
        btn[1]=(Button)findViewById(R.id.question_btn);
        btn[2]=(Button)findViewById(R.id.search_btn);
        //设置ViewPager页面格式
        viewPager = (ViewPager)findViewById(R.id.pager_view);
        View page_main = LayoutInflater.from(this).inflate(R.layout.page_main,null);
        View page_question = LayoutInflater.from(this).inflate(R.layout.page_question,null);
        View page_search = LayoutInflater.from(this).inflate(R.layout.page_search,null);
        //封装的方法初始化;
        initSettingbth();
        initSeachAnswer(page_search);
        initQuestionList(page_question);

        viewPager.setOffscreenPageLimit(3);//必须加上;
        allViews = new ArrayList<>();
        allViews.addAll(Arrays.asList(page_main,page_question,page_search));
        Log.d("ts....", allViews.size() + "");
        pagerAdapter = new MyPagerAdapter(allViews);
        viewPager.setAdapter(pagerAdapter);
        //设置页面改变事件
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }
            //页面被选择时候的事件
            @Override
            public void onPageSelected(int position) {
                //设置被选中页面顶部文字
                top_title.setText(allTitles[position]);
                //设置按钮颜色变化
                for( int i = 0 ; i < btn.length ; i++){
                    if( i == position){
                        btn[i].setBackgroundResource(bottomImgsSelected[i]);
                    }else{
                        btn[i].setBackgroundResource(bottomImgs[i]);
                    }
                }
            }
            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    /**
     * question部分的具体代码
     */

    //文件、数据库、分页操作所需对象
    //从文件中读取数据得到list
    private List<Map<String,Object>> values;
    private QuestionAdapter questionAdapter;
    private ListView list;
    //分页所用数据
    private int pageSize = 15;
    private int pageNum = 1;
    private int pageCount;
    private int recordCount;
    //模糊查询关键字
    private String keyword;
    //数据条读取时，第一个可见项，可见项目的数量，总数目
    private int first;
    private int visible;
    private int total;

    public void initQuestionList(View questionView){
        list = (ListView)questionView.findViewById(R.id.list);
        if(keyword==null){
            keyword="";
        }
        //从数据库中按页读取数据
        values = QuestionDao.loadDataPage(pageNum,pageSize,keyword);
        recordCount = QuestionDao.getCount(keyword);
        pageCount = (recordCount - 1) / pageSize + 1;
        //加入footView
        final TextView footerView = new TextView(this);
        footerView.setText("正在加载数据，请稍候。。。。");
        footerView.setTextColor(Color.BLACK);
        footerView.setTextSize(12);
        list.addFooterView(footerView);
        //设置适配器
        questionAdapter = new QuestionAdapter(this,values);
        list.setAdapter(questionAdapter);
        //设置view的点击事件
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Map<String,Object> map = values.get(position);
                LinearLayout linear = (LinearLayout)view;
                if( linear.getChildCount()>1){
                    linear.removeViewAt(1);
                    map.put("showFlag",false);
                }else{
                    TextView answerView  = new TextView(MainActivity.this);
                    answerView.setText(map.get("answer").toString());
                    answerView.setTextSize(14);
                    answerView.setTextColor(Color.RED);
                    linear.addView(answerView);
                    map.put("showFlag",true);
                }
            }
        });
        //设置滚动事件
        list.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if(scrollState == SCROLL_STATE_IDLE && first+visible >= total &&total!=0){
                    if( pageNum < pageCount){
                        pageNum++;
                        values.addAll(QuestionDao.loadDataPage(pageNum,pageSize,keyword));
                        questionAdapter.notifyDataSetChanged();
                    }else {
                        list.removeFooterView(footerView);
                    }
                }
            }
            //将第一个可见项，可见项目的数量，总数目拿出去使用
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                first = firstVisibleItem;
                visible = visibleItemCount;
                total = totalItemCount;
            }
        });
    }

    /**
     * Search部分的代码;
     */

    //取得搜索框和搜索按钮
    private EditText searchEdit;
    private Button searchBtn;
    public void initSeachAnswer(View searchView){
        searchEdit = (EditText)searchView.findViewById(R.id.search_content);
        searchBtn = (Button)searchView.findViewById(R.id.search_btn);
        searchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //取得keyword的值,变量在question部分已经声明
                keyword = searchEdit.getText().toString();
                pageNum = 1;
                //要将以前values中的值清空
                values.clear();
                values.addAll(QuestionDao.loadDataPage(pageNum,pageSize,keyword));
                questionAdapter.notifyDataSetChanged();
                //to smoothly scroll to the new item,第一个参数是目标页面，第二个参数true 表示移动到目标页面
                viewPager.setCurrentItem(1,true);
            }
        });
    }

    /**
     * 顶部的设置按钮操作
     */
    //顶部设置按扭
    private Button settingbth;
    //PopupWindow用于产生浮动窗口
    private PopupWindow window;
    public void initSettingbth(){
        settingbth = (Button)findViewById(R.id.setting_btn);
        //设置顶部按钮事件
        settingbth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                window = new PopupWindow(Globals.SCREEN_WIDTH/4,Globals.SCREEN_HEIGHT/6);
                final View window_view = LayoutInflater.from(MainActivity.this).inflate(R.layout.window_list,null);
                window.setContentView(window_view);
                //一下两行代码设置点击空白处消失
                window.setBackgroundDrawable(new BitmapDrawable());
                window.setFocusable(true);
                //设置将窗口在按钮下方显示
                window.showAsDropDown(settingbth);
                TextView version = (TextView) window_view.findViewById(R.id.win_version);
                TextView about = (TextView) window_view.findViewById(R.id.win_about);
                TextView exit = (TextView) window_view.findViewById(R.id.win_exit);

                version.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        window.dismiss();
                        Toast.makeText(MainActivity.this,"当前为1.0.1版本",Toast.LENGTH_LONG).show();
                    }
                });
                about.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        window.dismiss();
                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        builder.setTitle("提示信息");
                        builder.setMessage("此应用为北航团队制作");
                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }

                        });
                        builder.create().show();
                    }
                });

                exit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
            }
        });
    }




}
